<?php

/**
 * This is the model class for table "posts". 
 * @property interger $like_id 
 * @property interger $post_id 
 * @property interger $post_id 
 * @property interger $time_created
 */
class Like extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return '{{likes}}';
    }

    public function relations() {
	return array(
	    'user' => array(self::BELONGS_TO, 'User', 'user_id'),
	    'cat' => array(self::BELONGS_TO, 'Category', 'category_id'),
	    'comment' => array(self::HAS_MANY, 'Comment', 'post_id')
	);
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	return array(
	    array('like_id, type_id, user_id, item_id, time_created', 'safe')
	);
    }

    public function afterSave() {
	parent::afterSave();
	if ($this->type_id == 'post') {//like for post
	    $modelPost = Posts::model()->find('post_id=' . $this->item_id);

	    //increase toatal like
	    $modelPost->total_like = $modelPost->total_like + 1;
	    $modelPost->save();
	} else {
	    if ($this->type_id == 'comment') {//like for comment
		$modelComment = Comment::model()->find('comment_id=' . $this->item_id);

		//increase toatal like
		$modelComment->total_like = $modelComment->total_like + 1;
		$modelComment->save();
	    }
	}
    }

    public function afterDelete() {
	parent::afterDelete();
	if ($this->type_id == 'post') {//unlike for post
	    $modelPost = Posts::model()->find('post_id=' . $this->item_id);

	    //decrease toatal like
	    $modelPost->total_like = $modelPost->total_like - 1;
	    $modelPost->save();
	} else {
	    if ($this->type_id == 'comment') {//unlike for comment
		$modelComment = Comment::model()->find('comment_id=' . $this->item_id);

		//decrease toatal like
		$modelComment->total_like = $modelComment->total_like - 1;
		$modelComment->save();
	    }
	}
    }

}
